package online.niuma.xiaocubao.controller;

import online.niuma.xiaocubao.common.Constants;
import online.niuma.xiaocubao.pojo.params.UpdatePasswordParam;
import online.niuma.xiaocubao.pojo.vo.LoginUserVo;
import online.niuma.xiaocubao.pojo.vo.Result;
import online.niuma.xiaocubao.pojo.vo.UpdateUserInfoParam;
import online.niuma.xiaocubao.service.IUserService;
import online.niuma.xiaocubao.utils.UserThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 一颗蛋50斤
 * @since 2022-11-06
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @GetMapping("/getUserInfo")
    public Result getUserInfo() {
        LoginUserVo loginUserVo = UserThreadLocal.get();
        return Result.success(loginUserVo);
    }

    @PostMapping("/updateUserInfo")
    Result updateUserInfo(@RequestHeader(Constants.HEAD_TOKEN) String token,
                          @RequestBody UpdateUserInfoParam updateUserInfoParam) {
        return userService.updateUserInfo(token, updateUserInfoParam);
    }

    @PostMapping("/updateUserPassword")
    public Result updateUserPassword(@RequestBody UpdatePasswordParam updatePasswordParam) {
        String oldPassword = updatePasswordParam.getOldPassword();
        String newPassword = updatePasswordParam.getNewPassword();
        return userService.updateUserPassword(oldPassword, newPassword);
    }

    @PostMapping("/updateAvatar")
    public Result updateUserAvatar(@RequestParam("file") MultipartFile file,
                                   @RequestHeader(Constants.HEAD_TOKEN) String token) {
        String originalFilename = file.getOriginalFilename();
        // 唯一文件名称
        String fileName = UUID.randomUUID() + "." + StringUtils.substringAfterLast(originalFilename, ".");
        return userService.updateUserAvatar(file, fileName, token);
    }

}
